// 二次封装axios
import axios from 'axios'
import {Message} from 'element-ui'
import router from '@/router'

// 引入环境地址
import env from './env'

// 闯进axios实例
const service = axios.create({
    baseURL:env.proEnv.baseURL,
    timeout:5000
})

// 设置请求ata拦截器
service.interceptors.request.use(config=>{
    if(config.url!=='/login'){
        const token=sessionStorage.getItem('token')
        token && (config.headers['Authorization']=token) 
    }
    console.log('请求拦截');
    return config
},error=>{})

service.interceptors.response.use(res=>{
    console.log('响应拦截器:',res);
    const {meta:{msg,status}}=res.data
    const StatusArr=[200,201,204]
    if(StatusArr.includes(status)){
        const {data} =res.data
        if(res.config.url==='/login'){
            console.log(11);
            sessionStorage.setItem('token',data.token)
            router.push('/home')
        }
        Message({
            message:msg,
            type:'success'
        })
        return data
    }
    
    Message({
        message:msg,
        type:'error'
    })
    return Promise.reject(msg)
})

export default service